package com.my.easymall.filter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.HashMap;
import java.util.Map;
/**
 * @auther Summerday
 */
public class MyHttpServletRequest extends HttpServletRequestWrapper {
    private HttpServletRequest request;
    private String encode;
    public MyHttpServletRequest(HttpServletRequest request,String encode) {
        super(request);
        this.request = request;
        this.encode = encode;
    }
    @Override
    public Map<String, String[]> getParameterMap() {
        try {
            Map<String, String[]> map = request.getParameterMap();
            //新map,存储处理后没有乱码的数据
            Map<String, String[]> rmap = new HashMap<>();
            //处理乱码数据
            for (Map.Entry<String, String[]> entry : map.entrySet()) {
                String key = entry.getKey();
                String[] values = entry.getValue();
                String[] rvalue = new String[values.length];
                for (int i = 0; i < values.length; i++) {
                    //针对tomcat8以前的get方法请求参数乱码问题
                    rvalue[i]=new String(values[i].getBytes("iso8859-1"), encode);
                }
                rmap.put(key,rvalue);
            }
            return rmap;
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
    @Override
    public String[] getParameterValues(String name) {
        return getParameterMap().get(name);
    }
    @Override
    public String getParameter(String name) {
        String[] values = getParameterValues(name);
        return values == null?null:values[0];
    }
}
